﻿#include "forward_task.h"

Forward_Task::Forward_Task(QTcpSocket* source, QTcpSocket* target, QObject *parent) : QObject(parent)
{
    mTcpSource = source;
    mTcpTarget = target;
}

void Forward_Task::run()
{
    qDebug()<<"new Task";
    
    //连接信号转发槽函数
    connect(mTcpSource,&QTcpSocket::readyRead,this,&Forward_Task::forwardDataToTarget);
    connect(mTcpTarget,&QTcpSocket::readyRead,this,&Forward_Task::forwardDataToSource);
    connect(mTcpSource,&QTcpSocket::disconnected,this,&Forward_Task::disconnected);
    connect(mTcpTarget,&QTcpSocket::disconnected,this,&Forward_Task::disconnected);
    
}

void Forward_Task::forwardDataToSource()
{
    QByteArray buff = mTcpTarget->readAll();
    mTcpSource->write(buff);
}

void Forward_Task::forwardDataToTarget()
{
    QByteArray buff = mTcpSource->readAll();
    mTcpTarget->write(buff);
}


void Forward_Task::disconnected()
{
    qDebug()<<"Task Disconnected";
    //回收socket到连接池塘
    if(mTcpSource != nullptr)
    {
        qDebug()<<"回收offer";
        emit RecycleSocket(mTcpSource);
    }
    if(mTcpTarget != nullptr)
    {
        qDebug()<<"释放client";
        mTcpTarget->disconnectFromHost();
        mTcpTarget->close();
        mTcpTarget->deleteLater();
    }
    this->deleteLater();
}

